package com.rtsapp.server.kzlog.api.logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 一个周期性的日志记录类
 * 日志记录是同步的
 */
public class RollingLogger {

    private static final String NEXT_LINE = "\n";


    private final String fileNamePattern ;
    private final String dateFormat;
    private final RollingCalendar calendar;

    private Writer loggerWriter = null;
    private long nextDayStartMills = 0;




    public RollingLogger( String fileNamePattern, String dateFormat ){

        RollingCalendar calendar = new RollingCalendar();
        calendar.setType(RollingCalendar.TOP_OF_DAY, 0);

        this.fileNamePattern = fileNamePattern;
        this.dateFormat = dateFormat;
        this.calendar = calendar;
    }


    public RollingLogger( String fileNamePattern, String dateFormat, RollingCalendar calendar){
        this.fileNamePattern = fileNamePattern;
        this.dateFormat = dateFormat;
        this.calendar = calendar;
    }


    public void appendLog( String log ){

        long timeMillis = System.currentTimeMillis();

        if( timeMillis > nextDayStartMills ){
            synchronized ( this ){
                if( timeMillis > nextDayStartMills ){
                    gotoNextPeriod( );
                }
            }
        }

        if( loggerWriter == null ){
            System.err.println("loggerWriter 为null, 不能记录日志, 下面是要记录的日志");
            System.err.println(log);
            return;
        }


        synchronized ( this ){
            try {
                loggerWriter.write( log );
                loggerWriter.write( NEXT_LINE );
                loggerWriter.flush();
            } catch (IOException e) {
                System.err.println("输出日志有错, 日志如下");
                System.err.println(log);
                e.printStackTrace(System.err);

            }

        }
    }


    private void gotoNextPeriod(){
        //如果当前writer不为空, 保存并关闭当前writer
        if( loggerWriter != null ){
            try {
                loggerWriter.flush();
                loggerWriter.close();
                loggerWriter = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Date now = new Date();
        SimpleDateFormat format =  new  SimpleDateFormat( dateFormat );
        String dateStr = format.format( now );

        String fileName = String.format(fileNamePattern, dateStr);
        File f = new File( fileName );

        if( ! f.exists() ){
            try {

                int index = f.getAbsolutePath().lastIndexOf( File.separator );
                File dir = new File( f.getAbsolutePath().substring( 0, index ) );
                if( ! dir.exists() ){
                    boolean createDirOK = dir.mkdirs();
                    if( !createDirOK ){
                        System.err.println( "创建日志目录失败:"  + dir.getAbsolutePath() );
                        return;
                    }
                }

                f.createNewFile();
            } catch (IOException e) {
                System.err.println("创建日志文件失败:" + f.getAbsolutePath());
                e.printStackTrace(System.err);
                return;
            }
        }

        try {
            loggerWriter = new FileWriter( f, true );
        } catch (IOException e) {
            System.err.println( "创建loggerWriter失败:" + f.getAbsolutePath()  );
            e.printStackTrace( System.err );
            return;
        }

        //计算下一个周期
        nextDayStartMills = calendar.getNextCheckMillis( now );

    }


}
